package com.smallchill.core.db;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import org.beetl.sql.core.IDAutoGen;
import org.beetl.sql.core.SQLManager;

import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import com.smallchill.core.redis.IJedis;
import com.smallchill.core.redis.IKeyNamingPolicy;
import com.smallchill.core.redis.RedisCluster;
import com.smallchill.core.redis.RedisSingle;
import com.smallchill.core.redis.serializer.JdkSerializer;

public class DAOManager {
	private static Map<String, SQLManager> sqlManagerPool = new ConcurrentHashMap<String, SQLManager>();
	private static Map<String, IJedis> redisCachePool = new ConcurrentHashMap<String, IJedis>();
	
	public String MASTER = "master";
	
	public Map<String, SQLManager> getSqlManagerPool(){
		return sqlManagerPool;
	}
	
	public Map<String, IJedis> getRedisCachePool(){
		return redisCachePool;
	}
	
	private DAOManager() { }
	
	private static DAOManager me = new DAOManager();
	
	public static DAOManager init(){
		return me;
	}
	
	public void register(String key, SQLManager sm) {
		//增加自定义@AssignID注解的值, 使用方式: @Assign("uuid")
		sm.addIdAutonGen("uuid", new IDAutoGen<String>() {
			public String nextID(String arg0) {
				return UUID.randomUUID().toString();
			}
		});
		sqlManagerPool.put(key, sm);
	}
	
	public void register(String key, JedisPool jedisPool) {
		//创建redis单机操作类
		RedisSingle rs = new RedisSingle(key, jedisPool, JdkSerializer.me, IKeyNamingPolicy.defaultKeyNamingPolicy);
		redisCachePool.put(key, rs);
	}
	
	public void register(String key, JedisCluster jedisCluster) {
		//创建redis集群操作类
		RedisCluster rc = new RedisCluster(key, jedisCluster, JdkSerializer.me, IKeyNamingPolicy.defaultKeyNamingPolicy);
		redisCachePool.put(key, rc);
	}


	public void destroy() {
		for (IJedis jedis : redisCachePool.values()) {
			jedis.close();
		}
		redisCachePool.clear();
		sqlManagerPool.clear();
	}
	
}
